<?php
namespace app\admin\controller;

use app\common\controller\Base;
use ocean\Arr;
use think\facade\View;

class Rule extends Base
{
    protected $config=[
        'modelName'=>'Rule'
    ];
    public function __construct()
    {
        parent::__construct();
        $this->model=model($this->config['modelName']);
    }
    /*
     * 列表
     */
    public function index()
    {
        $data=$this->model->select()->toArray();
        $data=(new Arr())->tree($data,'title');
        View::share(['data'=>$data]);
        return view();
    }
    /*
     * 添加
     */
    public function addC(){
        if($this->request->isPost()){
            $data=$this->request->post();
            $check=$this->validation('app\admin\validate\Rule',$data,'add');
            if($check['status']==0) $this->error($check['msg']);
            $res=$this->model->save($data);
            $res?$this->success('规则添加成功','index'):$this->error('执行错误','index');
        }
        //数据分配部分
        $data=$this->model->field('id,title,pid')->select()->toArray();
        $data=(new Arr())->tree($data,'title');
        //使用数状处理
        View::share(['title'=>'规则添加','pTree'=>$data]);
        return view('store');
    }
    /*
     * 编辑
     */
    public function editC($id){
        $id=intval($id);
        if($this->request->isPost()){
            $data=$this->request->post();
            $data['id']=$id;
            $check=$this->validation('app\admin\validate\Rule',$data);
            if($check['status']==0) $this->error('验证失败'.$check['msg']);
            $res=$this->model->save($data,$id);
            ($res)?$this->success('操作成功','index'):$this->error('操作失败'.$this->model->getError(),'index');
        }
        $oldData=$this->model->where('id',$id)->find();
        // 思路A: 1.找子集(需要全部数据),2.将子集追加进去,3,将这些数据排除在外,4,进行树形处理
        $ruleAll=$this->model->select()->toArray();
        $ruleTree=(new Arr())->tree_notchild($ruleAll,'title',$id);
        View::share(['title'=>'规则编辑','pTree'=>$ruleTree,'oldData'=>$oldData]);
        return view('store');
    }
    /*
     * 删除
     */
    public function delC(){
        if($this->request->isPost()){
            $data=$this->request->post();
            $check=$this->validation('app\admin\validate\Delete',$data,'del');
            if($check['status']==0) return '验证失败'.$check['msg'];
            $res=$this->model::destroy($data['id']);
            $back=$res?'删除成功':'删除失败'.$this->model->getError();
            return $back;
            // return json_encode($data);
        }
    }

}
